package com.hhxy.runner;

import com.hhxy.annotation.SystemLog;
import com.hhxy.constants.SystemConstants;
import com.hhxy.mapper.ArticleMapper;
import com.hhxy.model.entity.Article;
import com.hhxy.utils.redis.RedisCache;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ghp
 * @date 2023/3/24
 * @title
 * @description 用于数据预热
 */
@Component
public class ViewCountRunner implements CommandLineRunner {

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private RedisCache redisCache;

    /**
     * 预热数据（SpringBoot程序启动后，自动执行该方法）
     * @param args
     * @throws Exception
     */
    @Override
    @SystemLog(businessName = "预热Redis中的数据")
    public void run(String... args) throws Exception {
        // 查询博客信息
        List<Article> articles = articleMapper.selectList(null);
        // 将查询出来的List数据转成Map，key为文章id，value为文章阅读量
        Map<String, Integer> viewCountMap = articles.stream()
                .collect(Collectors.toMap(article -> article.getId().toString(),
                        article -> article.getViewCount().intValue()));
        // 存储到redis中
        redisCache.setCacheMap(SystemConstants.ARTICLE_VIEW_COUNT, viewCountMap);
    }
}
